<?php

class Nimblecms_Controller_Plugin_Acl extends Zend_Controller_Plugin_Abstract {
	
	private $_acl = null;
	
	public function __construct() {
		
		if ($this->_acl === null)
			$this->_acl = new Nimblecms_Auth_Acl ();
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
		
		$auth = Zend_Auth::getInstance ();
		
		if ($auth->hasIdentity ()) {
			
			$storage = $auth->getStorage ()->read ();
			$user = Doctrine_Core::getTable('Users_Model_Users')->find($storage->id);
			if($user) {
				$user->last_ip = $request->getClientIp();
				$user->last_enter = time();
				$user->save();
			}
			$role = $storage->role;
		
		} else {
			$role = 'guest';
		}
		
		$uri = $request->getRequestUri();
		$uri = strtolower($uri);
		
		$uri = rtrim($uri, '/') . '/';
		if (strpos($uri, '/admin/') !== false) {
			$resource = 'admin';
		} else {
			$resource = null;
		}
		
		//$module = $request->getModuleName();
		//$action = $request->getActionName ();
		//$controller = $request->getControllerName ();
		
		//Resource is controller
		//$resource = $module . ':' . $controller;
		
		//Check Resource
		if (! $this->_acl->has ( $resource )) {
			$resource = null;
		}
		
		//Check Rules
		if (! $this->_acl->isAllowed ( $role, $resource, null )) {
			$request->setControllerName ( 'auth' )->setActionName ( 'login' );
		}
	
	}
}